﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Isha.Entities;
using Isha.Data.Infrastructure;
using Isha.Services;
using Isha.Repositories.Infrastructure;
using Isha.Services.Infrastructure;
using System.Web.Mvc;

namespace Isha.Services
{
    internal class SecurityService : ServiceBase, ISecurityService
    {

        public SecurityService()
        {
            Initialize(null, null, null);
        }

        public SecurityService(IUserRepository userRepository, IRoleRepository roleRepository, IUnitOfWork unitOfWork)            
        {
            Initialize(userRepository, roleRepository, unitOfWork);
        }

        public IUserRepository UserRepository { get; private set; }

        public IRoleRepository RoleRepository { get; private set; }

        public IUnitOfWork UnitOfWork { get; private set; }

        void Initialize(IUserRepository userRepository, IRoleRepository roleRepository, IUnitOfWork unitOfWork)
        {
            UserRepository = (userRepository ?? DependencyResolver.Current.GetService<IUserRepository>());
            RoleRepository = (roleRepository ?? DependencyResolver.Current.GetService<IRoleRepository>());
            UnitOfWork = (unitOfWork ?? DependencyResolver.Current.GetService<IUnitOfWork>());
        }

        public IEnumerable<User> GetUsers()
        {
            var users = UserRepository.GetAll();
            return users;
        }

        public User GetUser(string userName)
        {
            var user = UserRepository.Find(userName);
            return user;
        }

        public void CreateUser(User user)
        {
            UserRepository.Add(user);
            UnitOfWork.Commit();
        }

        public void DeleteUser(string userName)
        {
            var user = GetUser(userName);
            UserRepository.Delete(user);
            UnitOfWork.Commit();
        }

        public IEnumerable<Role> Roles()
        {
            var roles = RoleRepository.GetAll();
            return roles;
        }

        public Role GetRole(string roleName)
        {
            var role = RoleRepository.Find(roleName);
            return role;
        }

        public void CreateRole(Role role)
        {
            RoleRepository.Add(role);
            UnitOfWork.Commit();
        }

        public void DeleteRole(string roleName)
        {
            var role = GetRole(roleName);
            RoleRepository.Delete(role);
            UnitOfWork.Commit();
        }
        public void AssignRole(string userName, List<string> roleNames)
        {
            UserRepository.AssignRole(userName, roleNames);
            UnitOfWork.Commit();
        }       
    }
}
